package eu.news.servlet.admin.news;

import java.io.IOException;
import java.net.URLDecoder;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import eu.jk.base.security.AuthFilter;
import eu.news.data.hibernate.dao.HB_SortDAO;
import eu.news.data.pojo.Sort;
import eu.news.kits.JsonUtil;

/**
 * Servlet implementation class ListSort
 */
public class ListSort extends HttpServlet {
	
	private static final long serialVersionUID = 1L;
     
	private static final int BLOCK_SIZE=50;
    /**
     * @see HttpServlet#HttpServlet()
     */
    public ListSort() {
        super();
        // TODO Auto-generated constructor stub
    }

	/**
	 * @see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse response)
	 */
	protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		request.getRequestDispatcher("/admin/news/sort/list.jsp").forward(request, response);
	}

	/**
	 * @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse response)
	 */
	protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		String[] fields=request.getRequestURI().split("/");
		String spName=null;
		for(int i=0;i<fields.length;i++)
			if("list".equals(fields[i])&&i!=0){
				spName=fields[i];
				if(i<fields.length-1)
					spName=URLDecoder.decode(fields[i+1],"UTF-8");
			}
		String _page=request.getParameter("page");
		int page=0;
		if(AuthFilter.isDigit(_page))
			page=Integer.parseInt(_page);
		if(spName!=null){
			StringBuffer buffer=new StringBuffer("{\"sorts\":[");
			HB_SortDAO dao=new HB_SortDAO();
			for(Sort sort: dao.getBySpecialName(spName,page*BLOCK_SIZE,BLOCK_SIZE)){
				JsonUtil json=new JsonUtil();
				json.put("name", sort.getName());
				buffer.append(json.toString());
				buffer.append(",");
			}
			if(buffer.length()>10)
				buffer.deleteCharAt(buffer.length()-1);
			buffer.append("]}");
			response.setCharacterEncoding("UTF-8");
			response.getWriter().print(buffer);
		}
	}

}
